package com.smart.community.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;


public class CommonBeanutils extends BeanUtils {
    /**
     * 将单个对象复制从两个代码变成一行代码
     * Brand brand = CommonBeanutils.convertTo(brandQO, Brand::new);
     */
    public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) {
        if (ObjectUtils.isEmpty(source) || ObjectUtils.isEmpty(targetSupplier)) {
            return null;
        }
        T t = targetSupplier.get();
        copyProperties(source, t);
        return t;
    }

    /**
     * PageInfo
     * List<><
     *
     * @param sources
     * @param targetSupplier
     * @return
     */
    public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
        if (null == sources || null == targetSupplier) {
            return null;
        }
        return sources.stream().map(s -> convertTo(s, targetSupplier)).collect(Collectors.toList());
    }

    /**
     * PageInfo<ProductCategory> pageInfo
     * <p>
     * <p>
     * <p>
     * * PageInfo<ProductCategoryVo> pageInfoVo
     *
     * @param source
     * @param target
     * @param targetSupplier
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> IPage<T> convertPageInfo(IPage<S> source, IPage<T> target, Supplier<T> targetSupplier) {
        copyProperties(source, target);
        target.setRecords(convertListTo(source.getRecords(), targetSupplier));
        return target;
    }

}
